package com.chisheng.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Mybatis 会话获取工具
 *
 * @author chisheng
 * @since 2021-11-05
 */
public class MybatisUtils {

    /**
     * SQL 会话工厂
     */
    private static SqlSessionFactory factory;

    static {
        try {
            InputStream in = Resources.getResourceAsStream("mybatis.config.xml");
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回 SqlSessionFactory
     */
    @SuppressWarnings("unused")
    public static SqlSessionFactory getSessionFactory() {
        return factory;
    }

    /**
     * 返回 SqlSession
     */
    public static SqlSession getSqlSession() {
        return factory.openSession();
    }

}
